package com.example.role_based_permission_control.api;

import com.example.role_based_permission_control.entity.dto.User;
import com.example.role_based_permission_control.entity.dto.UserLoginDTO;
import com.example.role_based_permission_control.service.IUserService;
import com.example.role_based_permission_control.util.CustomResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 李云龙
 * @program: homework1
 * @description: 用户接口
 * @date 2024-08-19 23:45:10
 */

@RestController
public class UserController {
    @Autowired
    private IUserService userService;


    // 处理/login端点的HTTP POST请求
    @PostMapping("/login")
    public ResponseEntity<CustomResponse> login(@RequestBody UserLoginDTO loginUser, HttpServletRequest request) {
        //尝试根据提供的凭据对用户进行身份验证
        User user = userService.login(loginUser);
        CustomResponse response = null;
        // 检查身份验证是否成功
        if (user != null) {

            // 想实现未登录时无法访问其他接口，可以使用多种方式，比如：jwt，session等，
            // jwt适用于分布式系统和微服务架构,session 管理适合中小型单体 Web 应用，我们这里是一个基于 session 的实现方案。
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            response = new CustomResponse(200, "Login successful!", user);
            return ResponseEntity.ok(response);
        } else {
            response =
                    new CustomResponse(401, "Login failed. Invalidusername or password.", null);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
}


